package com.dingwen.treasure.security.exception;

import cn.hutool.json.JSONUtil;
import com.dingwen.treasure.base.pojo.vo.Result;
import com.dingwen.treasure.base.pojo.vo.ResultGenerator;
import lombok.Cleanup;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Serializable;


/**
 * 认证异常处理返回
 *
 * @author dingwen
 * @date 2022/06/13
 */
@Component
public class TreasureAuthenticationEntryPoint implements AuthenticationEntryPoint, Serializable {
    private static final long serialVersionUID = -6338034230832086286L;

    /**
     * 当用户尝试访问需要权限才能的REST资源而权限不足的时候，
     * 将调用此方法发送403响应以及错误信息
     */
    @SuppressWarnings("ALL")
    @Override
    public void commence(HttpServletRequest request,
                         HttpServletResponse response,
                         AuthenticationException authException) throws IOException {
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        Result<Object> failureResult = ResultGenerator.genFailureResult(authException.getMessage(), HttpStatus.FORBIDDEN.value());
        @Cleanup
        PrintWriter writer = response.getWriter();
        writer.print(JSONUtil.toJsonPrettyStr(failureResult));
    }
}

